const { DataTypes } = require('sequelize');
const bcrypt = require('bcryptjs');
const sequelize = require('../config/database');

// 定义用户模型
const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: { msg: '用户名不能为空' },
      len: { args: [2, 20], msg: '用户名长度必须在2-20个字符之间' }
    }
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: { msg: '请输入有效的邮箱地址' },
      notEmpty: { msg: '邮箱不能为空' }
    }
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: { msg: '密码不能为空' },
      len: { args: [6, 20], msg: '密码长度必须在6-20个字符之间' }
    }
  },
  role: {
    type: DataTypes.ENUM('admin', 'company', 'job-seeker'),
    allowNull: false,
    defaultValue: 'job-seeker',
    validate: {
      isIn: { args: [['admin', 'company', 'job-seeker']], msg: '角色必须是admin、company或job-seeker' }
    }
  },
  companyName: {
    type: DataTypes.STRING,
    allowNull: true,
    validate: {
      len: { args: [0, 50], msg: '公司名称不能超过50个字符' }
    }
  },
  phone: {
    type: DataTypes.STRING,
    allowNull: true,
    validate: {
      isMobilePhone: { args: 'zh-CN', msg: '请输入有效的手机号码' }
    }
  },
  avatar: {
    type: DataTypes.STRING,
    allowNull: true
  },
  status: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  }
}, {
  tableName: 'users',
  timestamps: true,
  underscored: true,
  hooks: {
    // 密码加密
    beforeCreate: async (user) => {
      if (user.password) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    },
    beforeUpdate: async (user) => {
      if (user.changed('password')) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    }
  }
});

// 密码验证方法
User.prototype.validPassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

// 关联关系
User.associate = (models) => {
  // 公司用户拥有多个职位
  User.hasMany(models.Job, {
    foreignKey: 'companyId',
    as: 'jobs'
  });
  // 用户拥有一份简历
  User.hasOne(models.Resume, {
    foreignKey: 'userId',
    as: 'resume'
  });
};

module.exports = User;